<?php

/**
 * Ocpc广告回调
 */

namespace App\Helpers;

use App\Service\ReqService;
use Hyperf\Utils\Context;
use App\Model\Ocpc\OcpcBaiduLog;

class OcpcUtil
{
    //激活
    const TYPE_ACTIVE = 1;
    //注册
    const TYPE_REG = 2;
    //付费
    const TYPE_PAY = 3;
    //首次付费
    const TYPE_FIRST_PAY = 4;

    /**
     * 百度回传
     */
    static function pushBaidu($type, $info,$akey='')
    {
//        $config = config('ocpc.channel');
//        $channel = $config[$info['channel']] ?? [];
//        if (!$channel) return false;
//        $akey = $channel['akey'] ?? '';
        if (!$akey) return false;
        $url = $info['url'];
        $find = ["{{ATYPE}}", "{{AVALUE}}"];
        switch ($type) {
            case self::TYPE_REG:
                $aType = 'register';
                break;
            case self::TYPE_PAY:
                $aType = 'orders';
                break;
            default:
                $aType = 'activate';
                break;
        }
        $url = urldecode($url);
        $aValue = $info['pay_amount'] ?? 0;
        $url = str_replace($find, [$aType, $aValue], $url);
        $sign = md5($url . $akey);
        // 得到最终callback url
        $url = $url . '&sign=' . $sign;
        $res = Helper::httpReq($url, [], 'urlencoded', 'get');
        log_info(__CLASS__ . "==pushBaidu=={$url}==" . json_encode($res));
        $res = json_decode($res, true);
        $result = [
            "error_code" => ($res['error_code'] ?? $res['errorCode']) ?? 1000,
            "error_msg" => ($res['error_msg']) ?? substr($res['errorMsg'], 0, 100) ?? "",
        ];
        return [
            'url' => $url,
            'pay_amount' => $aValue,
            'sign' => $sign,
            'res' => json_encode($result),
            'type' => $type,
            'channel' => $info['channel'] ?? 0,
            'pkg'   => empty(OcpcBaiduLog::PKG[$info['channel']]) ? '': OcpcBaiduLog::PKG[$info['channel']],
            'akeys' => $akey
        ];
    }

    static function pushKshou($type, $info)
    {
        $url = 'http://ad.partner.gifshow.com/track/activate';
        log_info(__CLASS__.':url'.$url);

        switch ($type) {
            case self::TYPE_REG:
                $aType = 2;
                break;
            case self::TYPE_PAY:
                $aType = 3;
                break;
            default:
                $aType = 1;
                break;
        }


        $url .= '?event_type='.$aType.'&event_time='.DateUtil::getCurrent13BitTimestamp().'&callback='.$info['callback'];


        if ($aType == 3) {
            $url .= '&purchase_amount='.$info['pay_amount'];
        }
        log_info(__CLASS__.__FUNCTION__.':url'.$url);
        $res = ReqService::reqGet($url);
        log_info(__CLASS__.':返回数据'.$res);

        return [
            'url' => $url,
            'pay_amount' =>  $info['pay_amount'] ?? 0,
            'res' => $res,
            'type' => $type,
            'pkg' => ConfigUtil::getPkgName($info['app_id']),
            'imei' => $info['imei'],
            'oaid' => $info['oaid']
//            $data['pkg'] = ConfigUtil::getPkgName($info['app_id']);
        ];
    }

    /**
     * @param $type
     * @param $info
     * @return array
     */
    static function pushBaiduSearch($type, $info): array
    {
        $url = urldecode($info['callback']);
        log_info(__CLASS__.':url'.$url);
        $config = config('ocpc.channel.'.$info['channel']);
        log_info(__CLASS__.':url'.$url);
        switch ($type) {
            case self::TYPE_REG:
                $aType = 'register';
                break;
            case self::TYPE_PAY:
                $aType = 'orders';
                break;
            default:
                $aType = 'activate';
                break;
        }

        log_info(__CLASS__.':url'.$url);
        $url = str_replace('{{ATYPE}}', $aType, $url);
        $url = str_replace('{{AVALUE}}',  $info['pay_amount'] ?? 0, $url);

        $sign = md5($url . $config['aKey']);
        log_info(__CLASS__.':sign'.$sign);
        $url = $url . '&sign=' . $sign;

        if(isset($info['oaid']) && $info['oaid']) {
            $url = $url . '&join_type=oaid';
        }else{
            $url = $url . '&join_type=imei';
        }
//        $url = $url.'&join_type=oaid';
        log_info(__CLASS__.':url'.$url);
        $res = ReqService::reqGet($url);
        log_info(__CLASS__.':返回数据百度搜索'.$res);

        log_info(__CLASS__.':返回数据百度搜索请求'.$url);
//        $res = Helper::httpReq($url, [], 'urlencoded', 'get');

        return [
            'url' => $url,
            'pay_amount' =>  $info['pay_amount'] ?? 0,
            'sign' => $sign,
            'res' => $res,
            'type' => $type,
            'pkg' => ConfigUtil::getPkgName($info['app_id']),
            'imei' => $info['imei'],
            'oaid' => $info['oaid']
//            $data['pkg'] = ConfigUtil::getPkgName($info['app_id']);
        ];
    }

    /**
     * @param $type
     * @param $info
     * @return array|array[]
     */
    static function pushTencent($type, $info): array
    {
        $url = urldecode($info['callback']);
        log_info(__CLASS__.':请求 URLTencent:params'.json_encode($url));
        $params = [
            'actions' => []
        ];

        $paramsConfig = [
            'user_id' => [
                'hash_oaid' => md5($info['oaid']),
                'muid' => md5($info['imei']),
                'oaid' => $info['oaid']
            ]
        ];

        if($type==self::TYPE_PAY){
//            $dataType = 'active_pay';
            $paramsConfig['action_type'] = 'PURCHASE';
            $paramsConfig['action_param'] = [
                'value' => $info['pay_amount'] ?? 0
            ];
        }else{
//            $dataType = 'active_register';
            $paramsConfig['action_type'] = 'REGISTER';
        }

        $params['actions'][] = $paramsConfig;

        $result = ReqService::reqPostJson($params,$url);
//        $result = Helper::httpReq($url, json_encode($params), 'json');

        log_info(__CLASS__.':返回数据Tencent'.$result);

        log_info(__CLASS__.':返回数据Tencent:params'.json_encode($params));

        $data = $params;
        $data['imei'] = $info['imei'];
        $data['user_id'] = $info['user_id'];
        $data['oaid'] = $info['oaid'];
        $data['sign'] = 'sign';
        $data['pkg'] = ConfigUtil::getPkgName($info['app_id']);
        $data['res'] = $result;
        return $data;
    }

    /**
     * 回传抖音
     * @param $type
     * @param $info
     * @return array
     */
    static function pushDouYin($type,$info)
    {
        $appId = $info['app_id'];
        log_info(__CLASS__.'dyCallback:'.json_encode($info));
        $config = config('ocpc.channel.1010');
        $url = $config['url'];

        if($type==self::TYPE_PAY){
//            $dataType = 'active_pay';
            $params = [
                'event_type' => 'active_pay',
                'context' => [
                    'ad' => [
                        'callback' => $info['callback']
                    ]
                ],
                'properties' => [
                    'pay_amount' => $info['pay_amount'] ?? 0
                ],
                'timestamp' => time(),
            ];
        }else{
//            $dataType = 'active_register';
            $params = [
                'event_type' => 'active_register',
                'context' => [
                    'ad' => [
                        'callback' => $info['callback']
                    ]
                ],
                'timestamp' => time(),
            ];
        }


//        $params = [
//            'callback' => $info['callback'],
//            'conv_time' => time(),
//            'event_type' => $dataType,
//            'os' => $info['os'] ?? 0,
//            'idfa' => $info['idfa'] ?? '',
//            'imei' => $info['imei'] ?? '',
//            'oaid' => $info['oaid'] ?? ''
//        ];
//        $result = Helper::httpReq($url, $params, 'json');
        $result = ReqService::reqPostJson($params,$url);
//        $result = Helper::httpReq($url, json_encode($params), 'json', 'post');

        log_info(__CLASS__.':返回数据dy'.$result);

        log_info(__CLASS__.':返回数据dy:params'.json_encode($params));

        $data = $params;
        $data['imei'] = $info['imei'];
        $data['user_id'] = $info['user_id'];
        $data['oaid'] = $info['oaid'];
        $data['pkg'] = ConfigUtil::getPkgName($appId);
        $data['res'] = $result;
        return $data;
    }

    static function pushOppo($type = self::TYPE_ACTIVE, $info = [], $aid = 0)
    {
        //$appId = Context::get('app_id');
        $appId = $info['app_id'];
//        $config = config('ocpc.channel.504');
        $config = config('ocpc.channel.1002');
        if (!$config) return false;
        $url = $config['url'];
        $salt = $config['salt'];
        $base64Key = $config['base64Key'];

        if($type==self::TYPE_PAY){
            $dataType = 7;
        }else{
            $dataType = $type;
        }

        $timeStamp = intval(microtime(true) * 1000);
        $verifyType = 0;//IMEI为md5加密时 type=1

        $params = [
            'payAmount' => $info['pay_amount'] ?? 0,
            'appType' => 1,
            'dataType' => $dataType,
            'ascribeType' => 1,
            'channel' => 1,
            'type' => $verifyType,
            'pkg' => ConfigUtil::getPkgName($appId),
            'timestamp' => $timeStamp,
            'adId' => $aid
        ];

        if(!empty($info['imei'])){
            $params['imei'] = openssl_encrypt($params['imei'], 'AES-128-ECB', base64_decode($base64Key), 0, "");
        }elseif (!empty($info['oaid'])){
            $params['ouId'] = openssl_encrypt($info['oaid'], 'AES-128-ECB', base64_decode($base64Key), 0, "");
        }

        $str = json_encode($params) . $timeStamp . $salt;
        $headers['signature'] = md5($str);
        $headers['timestamp'] = (string)$timeStamp;
        $result = Helper::httpReq($url, $params, 'json', 'POST', $headers);

        log_info('返回数据oppo'.json_encode($result));

        log_info('返回数据oppo:params'.json_encode($params));

        $data = $params;
        $data['imei'] = $info['imei'];
        $data['user_id'] = $info['user_id'];
        $data['oaid'] = $info['oaid'];
        $data['sign'] = $headers['signature'];
        $data['res'] = $result;
        return $data;
    }


    static function pushVivo($type,$info){
//        $config = config('ocpc.channel.503');

//        if ($info['channel'] == '403') {
//            $config = config('ocpc.channel.403');
//        }

        if ($info['channel'] == '1003') {
            $config = config('ocpc.channel.1003');
        }

        $time = intval(microtime(true) * 1000);

        $url = $config['url']."?access_token=".$config['access_token']."&timestamp=".$time."&nonce=".uniqid('',true)."&advertiser_id=".$config['advertiser_id'];
        $appId = $info['app_id'];

        $dataList = [];

        if(!empty($info['imei'])){
            $dataList['userIdType'] = 'IMEI';
            $dataList['userId'] = $info['imei'];
        }elseif(!empty($info['oaid'])){
            $dataList['userIdType'] = 'OAID_MD5';
            $dataList['userId'] = $info['oaid_md5'];
        }

        if($type==2){
            //注册
            $dataList['cvType'] = 'REGISTER';
        }elseif ($type==3){
            //充值
            $dataList['cvType'] = 'PAY';
        }

        $dataList['cvTime'] = $time;
        $dataList['cvParam'] = $info['pay_amount'] ? (string)$info['pay_amount'] : '0';
        $pak = ConfigUtil::getPkgName($appId);
        $params = [
            'srcType'=>'app',
            'pkgName'=>$pak,
            'srcId'=>$config['src_id'],
            'dataList'=>[
                $dataList
            ],
        ];
        $headers['Content-Type'] = 'application/json;charset=utf-8';
        $result = Helper::httpReq($url, $params, 'json', 'POST', $headers);
        log_info('返回错误数据'.json_encode($result));
        $data = $params;
        $data['imei'] = $info['imei'];
        $data['oaid'] = $info['oaid_md5'];
        $data['pay_amount'] = $info['pay_amount'] ?? 0;
        $data['pak'] = $pak;
        $data['res'] = $result;
        $data['user_id'] = $info['user_id'];
        return $data;

    }


    /**
     * Uc回传
     * @param int $type
     * @param array $info
     */
    public static function pushUc(int $type = self::TYPE_ACTIVE, array $info = [])
    {
        switch ($type) {
            case self::TYPE_REG:
                $aType = 27;
                break;
            case self::TYPE_PAY:
                $aType = 1000;
                break;
            default:
                $aType = 1;
                break;
        }
        $url = $info['url'];
        $oaid = strtoupper($info['oaid'] ?? '');
        $amount = ($info['pay_amount'] ?? 0) / 100;
        $t = DateUtil::msectime();
        //类型、oaid.金额(元)
        $url = sprintf($url . '&imei_sum=&type=%s&oaid=%s&money=%s&event_time=%s', $aType, $oaid, $amount, $t);
        $res = Helper::httpReq($url, [], 'urlencoded', 'get');
        log_info(__CLASS__ . "==pushUc=={$url}==" . json_encode($res));
        $res = json_decode($res, true);
        $result = [
            "status" => $res['status'] ?? -1,
            "message" => ($res['message']) ?? substr($res['message'], 0, 100) ?? "",
        ];
        return [
            'url' => $url,
            'pay_amount' => $amount * 100,
            'res' => json_encode($result),
            'type' => $type,
        ];
    }

    public static function pushXiaoMi($type, $info)
    {
        $config = config('ocpc.channel.xiaomi_moyu_rg');
        $convType = 'APP_PAY';
        if($type == 2){//注册
            if($info['channel'] == 505){
                $config = config('ocpc.channel.xiaomi_moyu_rg');
            }elseif($info['channel'] == 405){
                $config = config('ocpc.channel.xiaomi_mowan_rg');
            } elseif ($info['channel'] == 1005) {
                $config = config('ocpc.channel.xiaomi_leyu_rg');
            }
            $convType = 'APP_REGISTER';
        } elseif ($type == 4) {
            // 首次付费
            if ($info['channel'] == 505) {
                return '';
            } elseif ($info['channel'] == 405) {
                $config = config('ocpc.channel.xiaomi_mowan_first_pay');
            } elseif ($info['channel'] == 1005) {
                $config = config('ocpc.channel.xiaomi_leyu_first_pay');
            }

            $convType = 'APP_FIRST_PAY';
        } else{
            if($info['channel'] == 505){
                $config = config('ocpc.channel.xiaomi_moyu_pay');
            }elseif($info['channel'] == 405){
                $config = config('ocpc.channel.xiaomi_mowan_pay');
            } elseif ($info['channel'] == 1005) {
                $config = config('ocpc.channel.xiaomi_leyu_pay');
            }
        }

        log_info('小米配置'.json_encode($config));
        //query_string
        $oaid = urlencode($info['oaid']);
        $time = intval(microtime(true) * 1000);
        $client_ip = urlencode($info['client_ip']);
        $query_string = "oaid={$oaid}&conv_time={$time}&client_ip={$client_ip}";

        //参数签名
        $sign_key = $config['sign_key']; //"gmkIRIMpaXBytoYF";
        $property = $sign_key . "&" . urlencode($query_string);
        $signature = md5($property);

        //参数加密
        $base_data = $query_string . "&sign=" . urlencode($signature);

        $encrypt_key = $config['encrypt_key'];//"aftZEXiftmfXjFno";
        $get_xor = self::getXOR($base_data, $encrypt_key);
        $data = urlencode(base64_encode($get_xor));
        $appId = $config['app_id'];
        $customerId = $config['customer_id'];
        $amount = ($info['pay_amount'] ?? 0) / 100;
        $url = "http://trail.e.mi.com/global/log?appId={$appId}&info={$data}&conv_type={$convType}&customer_id={$customerId}&conv_weight={$amount}";
        $res = Helper::httpReq($url, [], '', 'get');
        log_info('小米测试'.json_encode($res));
        json_encode('ooooid'.json_encode($info['oaid']));
        //包名
        $pak = ConfigUtil::getPkgName($info['app_id']);
        $ret = [];
        $ret['oaid'] = $info['oaid'];
        $ret['imei'] = '';
        $ret['pay_amount'] = $info['pay_amount'] ?? 0;
        $ret['pak'] = $pak;
        $ret['res'] = $res;
        $ret['user_id'] = $info['user_id'];
        return $ret;
    }

    /**
     * 位运算
     * @param $data
     * @param $key
     * @param string $string
     * @return mixed|string
     */
    public static function getXOR($data, $key, $string = ''){
        $len = strlen($data);
        $len2 = strlen($key);
        for($i = 0; $i < $len; $i ++){
            $j = $i % $len2;
            $string .= ($data[$i]) ^ ($key[$j]);
        }
        return $string;
    }
}
